<?php

/**
 * contact : 刘经理 19326416371
 * company : 版权所属 四川北星惯牌科技有限公司
 **/

namespace app\admin\command\Project;

use app\admin\model\AuthRule;
use app\common\model\Match;
use app\common\model\Order;
use app\common\model\Team;
use app\common\model\UserCoupon;
use ReflectionClass;
use ReflectionMethod;
use think\Cache;
use think\Config;
use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Exception;
use think\Loader;

class Expire extends Command
{
    protected $model = null;

    protected function configure()
    {
        $this->setName('expire')
            ->setDescription('expire order deal with');
        //要执行的controller必须一样，不适用模糊查询
    }

    protected function execute(Input $input, Output $output)
    {
        $page = 1;
        $step = 100;
        try {
            $orderModel = new Order();
            while (true){
                $start = ($page-1)*$step;
                $info = $orderModel->where('pay_state',Order::PAY_STATE_INIT)->where('expire_time','<',time())->limit($start,$step)->select();
                if (!$info){
                    sleep(10);
                    continue;
                }
                foreach ($info as $k=>$v){
                    Db::startTrans();
                    try {
                        $v->pay_state = Order::PAY_STATE_EXPIRE;
                        $v->cancel_date = time();
                        $v->save();

                        if (!empty($v->relation_id)){
                            if ($v->type == Order::TYPE_TEAM){
                                $count = 0;
                                if ($v->assistant_ids){
                                    $assistant_ids = explode(',',$v->assistant_ids);
                                    $count = count($assistant_ids);
                                }
                                $orderedNum = $count + 1;
                                Team::where(['t_id'=>$v->relation_id,'ordered_number'=>Db::raw('ordered_number >= '.$orderedNum)])->update(['ordered_number'=>Db::raw('ordered_number - '.$orderedNum)]);
                            }else if ($v->type == Order::TYPE_MATCH){
                                Match::where(['m_id'=>$v->relation_id,'order_count'=>Db::raw('order_count >= 1 ')])->update(['order_count'=>Db::raw('order_count - 1')]);
                            }
                        }

                        if (!empty($v->user_coupon_id)){
                            UserCoupon::where(['id'=>$v->user_coupon_id,'block'=>UserCoupon::BLOCK_YES])->update(['block'=>UserCoupon::BLOCK_NO,'update_time'=>time()]);
                        }

                        Db::commit();
                    }catch (Exception $e){
                        Db::rollback();
                    }

                }

                $page++;
            }
        }catch (Exception $exception){

        }
    }

}
